package yang.VirtualMachine.chapter9.classStruct.constantPool;

import java.io.IOException;
import java.io.InputStream;

import yang.VirtualMachine.chapter9.ClassBean;
import yang.VirtualMachine.chapter9.ClassUtil;

/**
 * JDK1.7加入
 * u1 tag;u1 reference_kind;u2 reference_index
 * @author xinxin
 */
public class Con_MethodHandleProcesser implements PoolValue {
	/** 方法句柄的类型 */
	private int referenceKind;
	/** 方法句柄的位置 */
	private int referenceIndex;

	@Override
	public void process(InputStream input) throws IOException {
		referenceKind = (int) ClassUtil.getNumByStream(input, 1);
		referenceIndex = (int) ClassUtil.getNumByStream(input, 2);
	}

	@Override
	public String getValue() {
		PoolValue value = ClassBean.getInstance().constantPool[referenceIndex];
		return getKindValue() + ":" + value.getValue();
	}
	
	private String getKindValue() {
		// 常量池的指向内容必须是CONSTANT_Fieldref
		if (referenceKind == 1) return "REF_getField(1)";
		if (referenceKind == 2) return "REF_getStatic(2)";
		if (referenceKind == 3) return "REF_putField(3)";
		if (referenceKind == 4) return "REF_putStatic(4)";
		
		// 必须CONSTANT_Methodref（REF_invokeInterFace必须CONSTANT_InterfaceMethodref）
		// 且不能为<init>(对象实例化)或者<cint>(类加载),即不能为类的构造方法或者初始化方法
		if (referenceKind == 5) return "REF_invokeVirtual(5)";
		if (referenceKind == 6) return "REF_invokeStatic(6)";
		if (referenceKind == 7) return "REF_invokeSpecial(7)";
		if (referenceKind == 8) return "REF_invokeInterFace(9)";// 
		
		// 必须CONSTANT_Methodref,且必须为<init>
		if (referenceKind == 9) return "REF_newInvokeSpecial(8)";
		throw new RuntimeException("referenceKind error " + referenceKind);
	}

}
